package br.com.affero.model.dao;

import br.com.affero.hibernate.HibernateUtils;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;

public abstract class GenericDAO<T> {
    
    private HibernateUtils hibernateUtils;
    
    public GenericDAO() { 
        hibernateUtils = new HibernateUtils();
    }
    
    public void insert(T obj) throws HibernateException {
        Session session = hibernateUtils.openSession();
        Transaction transaction = session.beginTransaction();
        
        session.save(obj);
        transaction.commit();
        session.close();
    }
    
    public void update(T obj) throws HibernateException {
        Session session = hibernateUtils.openSession();
        Transaction transaction = session.beginTransaction();
        
        session.update(obj);
        transaction.commit();
        session.close();
    }
    
    public void delete(T obj) throws HibernateException {
        Session session = hibernateUtils.openSession();
        Transaction transaction = session.beginTransaction();
        
        session.delete(obj);
        transaction.commit();
        session.close();
    }
    
    public List<T> findAll(Class classe, String orderBy) throws HibernateException {
        Session session = hibernateUtils.openSession();
        Criteria criteria = session.createCriteria(classe);
        
        criteria.addOrder(Order.asc(orderBy));
        List lista = criteria.list();
        session.close();
        return lista;
    }
    
    public T findByPK(Integer codigo, Class classe) throws HibernateException {
        Session session = hibernateUtils.openSession();
        Transaction transaction = session.beginTransaction();
        Criteria criteria = session.createCriteria(classe);
        
        criteria.add(Expression.eq("codigo", codigo));
        T obj = (T) criteria.uniqueResult();
        transaction.commit();
        session.close();
        return obj;
    }
    
}
